package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    private final CategoryBrandService categoryBrandService;

    public BrandServiceImpl(CategoryBrandService categoryBrandService) {

        this.categoryBrandService = categoryBrandService;
    }


    @Override
    public BrandDTO findBrandById(long id) {

        return new BrandDTO(this.getById(id));
    }

    @Override
    public List<BrandDTO> listBrandById(List<Long> ids) {
        return BrandDTO.convertEntityList(this.listByIds(ids));
    }

    @Override
    public PageDTO<BrandDTO> pageQuery(Integer page, Integer rows, String key) {
        IPage iPage = new Page(page, rows);

        boolean condition = StringUtils.isNotBlank(key);

        page(iPage, new QueryWrapper<Brand>()
                .like(condition, "name", key)
                .or()
                .eq(condition, "letter", key)
        );


        List brands = BrandDTO.convertEntityList(iPage.getRecords());
        return new PageDTO<BrandDTO>(iPage.getTotal(),iPage.getPages(),brands);

    }

    @Override
    public List<BrandDTO> listBrandCategory(Long cid) {

        List<CategoryBrand> categoryBrands = this.categoryBrandService
                .query()
                .eq("category_id", cid)
                .list();
        if (CollectionUtils.isEmpty(categoryBrands)) {
            throw new LyException(204, "当前分类没有关联品牌");
        }
        return listBrandById(categoryBrands.stream().map(CategoryBrand::getBrandId).collect(Collectors.toList()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);

        //品牌新增，完成后，主键回显id，根据回显的品牌的id匹配提交的分类id，保存到中间表
        this.save(brand);

        if (CollectionUtils.isEmpty(brandDTO.getCategoryIds())) {
            throw new LyException(400, "此品牌对应的分类不能为空");
        }
        saveCategoryBrand(brandDTO.getCategoryIds(), brand.getId());

    }
    private void saveCategoryBrand(List<Long> cids, Long bid) {
        //根据分类id集合和品牌id，组合出中间表对象集合
        List<CategoryBrand> categoryBrands = cids
                .stream()
                .map(cid -> CategoryBrand.of(cid, bid))
                .collect(Collectors.toList());

        //保存中间表数据
        this.categoryBrandService.saveBatch(categoryBrands);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBrand(BrandDTO brandDTO) {

        //从dto转换为entity
        Brand brand = brandDTO.toEntity(Brand.class);

        this.updateById(brand);

        //品牌在修改过程中，分类是否发生了变化，1，变（变多了，变少了），2，没变

        //可以暴力操作，把之前的所有的关系，删除，然后重建关系

        //删除当前品牌对应的中间表的所有关系
        this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", brand.getId()));

        //判断更应该入口处，
        if (CollectionUtils.isEmpty(brandDTO.getCategoryIds())) {
            throw new LyException(400, "此品牌对应的分类不能为空");
        }

        //重建品牌和分类的关系
        saveCategoryBrand(brandDTO.getCategoryIds(), brand.getId());
    }

}